package org.ielts.service;

import org.ielts.domain.base.Course;
import org.ielts.domain.base.CourseType;
import org.ielts.repository.CourseTypeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class CourseTypeService {

	@Autowired
	CourseTypeRepository courseTypeRepository;

	@Transactional
	public CourseType createCourseType(String name, String title, String cssClass) {
		CourseType courseType = new CourseType();
		courseType.setName(name);
		courseType.setTitle(title);
		courseType.setCssClass(cssClass);

		courseTypeRepository.save(courseType);

		return courseType;
	}

	@Transactional
	public CourseType findCourseTypeByName(String name) {
		CourseType courseType = courseTypeRepository.findOneByName(name);

		return courseType;
	}

	@Transactional
	public Iterable<CourseType> findAll() {
		Sort sort = new Sort(new Order("name"));

		return courseTypeRepository.findAll(sort);
	}

	@Transactional
	public CourseType findOne(String id) {
		return courseTypeRepository.findOne(id);
	}

	@Transactional
	public CourseType modifyCourseType(String id, String name, String title, String cssClass) {
		CourseType courseType = courseTypeRepository.findOne(id);

		courseType.setId(id);
		courseType.setName(name);
		courseType.setTitle(title);
		courseType.setCssClass(cssClass);

		return courseType;
	}

	@Transactional
	public void removeCourseType(String id) {
		courseTypeRepository.delete(id);
	}

	@Transactional
	public void setCourseInType(String courseTypeId, String[] courseIds) {
		CourseType courseType = courseTypeRepository.findOne(courseTypeId);

		courseType.getCourses().clear();

		for (String courseId : courseIds) {
			Course course = new Course();
			course.setId(courseId);

			courseType.getCourses().add(course);
		}
	}
}
